package com.zjx.mhxykey;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.zjx.mhxykey.root.RootCmd;
import com.zjx.mhxykey.util.BitmapCutoutUtils;
import com.zjx.mhxykey.util.BitmapStringConverter;
import com.zjx.mhxykey.util.ImageLoader;


public class MainActivity extends AppCompatActivity {
    private Button startButton;
    private Button checkRoot;
    private TextView titleText;
    private TextInputEditText host;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        titleText = findViewById(R.id.titleText);
        host = findViewById(R.id.domainInput);

        startButton = findViewById(R.id.start_button);
        startButton.setOnClickListener(v -> {
            // 启动服务
            startKeepAliveService();

            // 隐藏应用
            hideApplication();
        });

        checkRoot = findViewById(R.id.check_root);
        checkRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RootCmd.haveRoot(null)){
                    titleText.append("手机已经Root"+"\n");
                    showMessage("手机已经Root");
                }else {
                    titleText.append("手机未Root"+"\n");
                    showMessage("手机未Root");
                }
            }
        });
    }

    public void test(){
        testCut();
//        saveToString();
    }

    private void testCut(){
        Bitmap screen = ImageLoader.loadFromExternalCache(this,BitmapConfig.screenFileName);
        for (int i = 0; i < 6; i++) {
            Rect rect = new Rect(160 + 68 * i,879,219+ 68 * i,974);
            Rect rect1 = new Rect(rect.left + 8,rect.top + 8,rect.right - 8,rect.bottom - 8);
            Bitmap cut = BitmapCutoutUtils.cutRect(screen,rect1);
            String ss = BitmapStringConverter.bitmapToHexString(cut);
            Log.d(this.getPackageName(),"已截图："+i+":"+ss);
        }
    }


    private void startKeepAliveService() {
        Intent serviceIntent = new Intent(this, KeepAliveService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }
    }

    private void hideApplication() {
        // 方法1：直接finish当前Activity
        finish();

        // 方法2：从最近任务列表中移除（可选）
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//            if (activityManager != null) {
//                List<ActivityManager.AppTask> appTasks = activityManager.getAppTasks();
//                if (appTasks != null && !appTasks.isEmpty()) {
//                    appTasks.get(0).setExcludeFromRecents(true);
//                }
//            }
//        }

        // 方法3：回到桌面（可选）
//        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
//        homeIntent.addCategory(Intent.CATEGORY_HOME);
//        homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(homeIntent);
    }

    public void showMessage(String message) {
        View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
        if (rootView != null) {
            Snackbar.make(rootView, message, Snackbar.LENGTH_SHORT).show();
        } else {
            // 回退方案
            showNotification("提示", message);
        }
    }

    private void showNotification(String title, String message) {
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "toast_channel",
                    "提示信息",
                    NotificationManager.IMPORTANCE_LOW
            );
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "toast_channel")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_LOW);

        notificationManager.notify((int) System.currentTimeMillis(), builder.build());
    }
}
